package searchTests;

import java.util.ArrayList;

public class BinSearch implements ISearch {

	@Override
	public int search(ArrayList<Integer> array, int elem) {
		return searchInner(array, elem, 0, array.size()-1);
	}
	
	private int searchInner(ArrayList<Integer> array, int elem, int l, int r) {
		if (r == l) {
			if (array.get(l) == elem) return l;
			else return -1;
		}
		int pivotIndex = (l+r)/2;
		int pivot = array.get(pivotIndex);
		if (elem == pivot) {
			return pivotIndex;
		} else {
			if (elem > pivot) return searchInner(array, elem, pivotIndex+1, r);
			else return searchInner(array, elem, l, pivotIndex-1);
		}
	}

}
